#include "RingQueue.hpp"
#include "Text.hpp"
#include <pthread.h>
#include <ctime>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>

std::string ThreadName()
{
    char name[128];
    snprintf(name, sizeof name, "thread[0x%x]", pthread_self());
    return name;
}

void *ConsumerRoutine(void *rq)
{
    // RingQueue<int> *ringqueue=static_cast<RingQueue<int>*>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        // version1
        // int data = rand()%10+1;
        // ringqueue->push(data);
        // std::cout<<"生产完成，生产的数据为："<<data<<std::endl;
        // sleep(1);

        // version2
        // 获取任务
        int x = rand() % 20;
        int y = rand() % 1500;
        char op = oper[rand() % oper.size()];
        Task t(x, y, op, mymath);
        // 生产任务
        ringqueue->push(t);
        std::cout << ThreadName() << "的生产完成,任务是：" << t.toTaskString() << std::endl;
    }
}

void *ProductorRoutine(void *rq)
{
    // RingQueue<int> *ringqueue=static_cast<RingQueue<int>*>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        // version1
        // int data;
        // ringqueue->pop(&data);
        // std::cout<<"消费完成，消费的数据为："<<data<<std::endl;

        // version2
        // 消费任务
        Task t;
        ringqueue->pop(&t);
        std::string ret = t();
        std::cout << ThreadName() << "的消费者消费任务：" << ret << std::endl;
        sleep(1);
    }
}

int main()
{
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self() ^ 0x71727374);
    // RingQueue<int> *rq=new RingQueue<int>();
    RingQueue<Task> *rq = new RingQueue<Task>();
    pthread_t c[8], p[4];
    for (int i = 0; i < 8; i++)
    {
        pthread_create(c + i, nullptr, ConsumerRoutine, rq);
    }
    for (int i = 0; i < 4; i++)
    {
        pthread_create(p + i, nullptr, ProductorRoutine, rq);
    }

    for (int i = 0; i < 4; i++)
    {
        pthread_join(p[i], nullptr);
    }
    for (int i = 0; i < 8; i++)
    {
        pthread_join(c[i], nullptr);
    }
    return 0;
}